import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../service/http.service";
import { Config } from "../../../service/config";
import { PartyBean } from "./bean/party.bean";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import { InspectionDetailPage } from "../../elevator/inspection-record/inspection-detail/inspection-detail";

@Component({
  selector: "party-page",
  templateUrl: "party.html",
  styleUrls: ["party.scss"]
})
export class PartyPage implements OnInit {
  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) { }
  //接收参数
  partyBean: PartyBean = new PartyBean();
  //系统类型
  searchOptions: any = Config.PARTY_TYPE;
  public nzSpinning: boolean = false; //遮罩
  config: any = Config;
  //返回的集合
  list: any = [];
  //总页数
  total: string;
  partyType: any;
  findType:any;
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  //设置add的
  isAddVisible = false;
  isAddConfirmLoading = false;
  inValue: string;
  currentModal: NzModalSubject;
  selectUtilModal : NzModalSubject;
  inPartyId: string; //传入组件的
  isConfirmLoading = false;
  modelTitle = "新增";
  updateData: any = {};
  modal: any = 0;
  totalList: any = [];
  upLoadParam: Object = {};

  type: any = "";
  sendtitle: any = "";
  userLevel : string = ""; //1：管理人员，2：其他人员：3：所有
  sendContent: any = "";

  partyList : any = [];
  partyTotal : string; //自定义发送通知机构分页数

  selectedUnitNames : string = "";
  selectedList : any = [];
  unitTypes : any = []; //选择的单位类别
  unitTypesList : any = []; //选择的单位列表
  userTypes : any = []; //选择的用户类型
  userTypesList : any = []; //单位对应的用户列表
  unitList : any;
  noticePartyType : string;



  ngOnInit() {
    this.partyBean.parentId = JSON.parse(
        window.localStorage.getItem("user")
      ).partyParentId;
    this.partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
    //当前机构的类型
    this.partyBean.id = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.upLoadParam["partyId"] = this.partyBean.id;
    this.partyBean.pageSize = 10;
    this.partyBean.currentPage = 1;
    this.partyBean.partyLevel = JSON.parse(window.localStorage.getItem("user")).partyLevel;
    this.partyBean.partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
    this.partyBean.findType = this.findType;
    this.query();

  }

  /**
   * 选择自定义发送通知的单位 1：维保单位 2：使用单位 3：检验机构 4：监管部门
   * @param param
   */
  selectUnit(titleTpl, contentTpl, footerTpl){
    this.partyBean.noticeCurrentPage = 1;
    this.partyBean.noticePageSize = 10;
    this.queryParty();
    let tempTitle = "选择单位";

    this.modelTitle = tempTitle;
    this.selectUtilModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 1000,
      zIndex: 1000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 选择单位类别后同时触发
   * @param $event 此参数未传的话就会出现参数滞后的情况。参数绑定未完成
   */
  unitTypeChangeAfter($event){
    if($event){
      let tempUnitTypes = $event;
      this.unitTypesList.splice(0,this.unitTypesList.length);
      this.userTypesList.splice(0,this.userTypesList.length);
      tempUnitTypes.forEach( element => {
        if(element == '1'){
          this.unitTypesList.push({name : '维保单位',value : '1'});
          this.getUserTypesList('1');
        }
        if(element == '2'){
          this.unitTypesList.push({name : '使用单位',value : '2'});
          this.getUserTypesList('2');
        }
        if(element == '3'){
          this.unitTypesList.push({name : '检验单位',value : '3'});
          this.getUserTypesList('3');
        }
        if(element == '4'){
          this.unitTypesList.push({name : '监管单位',value : '4'});
          this.getUserTypesList('4')
        }
      })
    }
  }

  /**
   * 根据选中的单位类型获取对应的单位下的用户类型列表
   */
  getUserTypesList(partyType){
    this.httpServcie.registerRoleList(partyType).subscribe(data=>{
      let tempList = data.data;
      if(data.status == '200'){
        tempList.forEach(ele =>{
          let isExit = false;
          this.userTypesList.forEach(element =>{
            if(element.value == ele.roleId){
              isExit = true;
            }
          });
          if(!isExit){
            this.userTypesList.push({name : ele.roleName, value : ele.id});
          }
        })
      }else{
        console.log("发送通知，获取用户类型异常");
      }
    });
  }

  /**
   * 保存已选机构单位
   */
  saveSelectedParty(){
    //再次点击时重新给值
    const tempList: any = [];
    this.partyList.forEach(element => {
      let isNotExist = true;
      if (element.checked) {
        tempList.push(element);
        this.selectedList.forEach(element1 =>{
          if(element.id == element1){
            isNotExist = false;
          }
        });
        if(isNotExist){
          this.selectedUnitNames = this.selectedUnitNames + element.partyName + ","
          this.selectedList.push(element.id + "");
        }
      }
    });
    if (tempList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "至少选中一条数据！");
      return;
    }
    this.selectUtilModal.destroy();
  }

  /**
   * 自定义发送通知，查询机构
   * @param page 1：主页面  ； 2：自定义发送通知页面
   */
  queryParty(){
    //获取选择的单位类型
    let tempUnitTypes = this.unitTypes;
    if(tempUnitTypes == null && typeof(tempUnitTypes) == "undefined"){
      this._notification.create("warning", "警告提示", "请先选择单位类别");
    }

    let tempPartyBean : PartyBean = new PartyBean();
    tempPartyBean.pageSize = this.partyBean.noticePageSize;
    tempPartyBean.currentPage = this.partyBean.noticeCurrentPage;
    tempPartyBean.partyName = this.partyBean.noticePartyName;
    if(this.noticePartyType != null){
      tempPartyBean.partyType = this.noticePartyType;
    }else{
      tempPartyBean.partyType = tempUnitTypes.join(",");
    }
    tempPartyBean.parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
    tempPartyBean.id = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.httpServcie.queryListParty(tempPartyBean).subscribe(
      data => {
        if (data.status === 200) {
          this.partyList = data.data.list;
          this.partyTotal = data.data.total;
          //再次点击，回显已选择
          this.partyList.forEach(element1 => {
            this.selectedList.forEach(element2 => {
              if (element1.id == element2) {
                element1.checked = true;
              }
            });
          });
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }



  /**
   * 重选后，清除已选择的内容
   * @param value
   */
  clearSelectedUnit(value){
    this.selectedUnitNames = "";
    this.selectedList.splice(0,this.selectedList.length);
  }

  /**
   * 自定义发送通知
   */
  sendMessage() {
    if (!this.sendtitle || !this.sendContent) {
      this._notification.create("error", "提示", "标题和内容必输!");
      return;
    }
    let param = {
      partyType: this.type,
      title: this.sendtitle,
      content: this.sendContent,
      id: JSON.parse(window.localStorage.getItem("user")).partyId,
      sendUserId: JSON.parse(window.localStorage.getItem("user")).id,
      partyIds : this.selectedList, //选择的单位集合
      userTypes : this.userTypes, //选择发送的用户类型
    };
    this.httpServcie.batchMsg(param).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "通知成功");
        this.clear();
        this.currentModal.destroy();
      } else {
        this._notification.create("error", "提示", "通知失败，请重试");
      }
    });
  }

  /**
   *消息发送成功清除表单中的内容
   */
  clear(){
    this.selectedUnitNames = "";
    this.sendtitle = "";
    this.sendContent = "";
    this.selectedList = [];
    this.userTypesList = [];
    this.unitTypesList = [];
    this.unitTypes = [];
    this.userTypes = [];
  }
  query() {
    if(this.findType !=null && this.findType !=""){
      this.partyBean.findType = this.findType;
    }
    this.nzSpinning = true;
    this.httpServcie.queryListParty(this.partyBean).subscribe(
      data => {
        if (data.status === 200) {
          this.nzSpinning=false;
          this.list = data.data.list;
          this.total = data.data.total;
          // 清空搜索
          this.partyBean.findType=null;


        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("warning", "警告提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value,page) {
    let checkList: any = [];
    if(page == 1){
      checkList = this.list;
    }
    if(page == 2){
      checkList = this.partyList;
    }
    if (value) {
      checkList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      checkList.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event,page) {
    if(page == 1){
      this.partyBean.pageSize = event;
      this.partyBean.currentPage = 1;
      this.query();
    }
    if(page == 2){
      this.partyBean.noticePageSize = event;
      this.partyBean.noticeCurrentPage = 1;
      this.queryParty();
    }
  }

  //输入框的方法
  nzPageIndexChange(event,page) {
    if(page == 1){
      this.partyBean.currentPage = event;
      this.query();
    }
    if(page == 2){
      this.partyBean.noticeCurrentPage = event;
      this.queryParty();
    }
  }

  //当前页
  nzPageIndexClickChange(event,page) {
    if(page == 1){
      this.partyBean.currentPage = event;
      this.query();
    }
    if(page == 2){
      this.partyBean.noticeCurrentPage = event;
      this.queryParty();
    }
  }

  //添加
  //this.isAddVisible = true;
  add(titleTpl, contentTpl, footerTpl) {
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }

    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //修改
  update(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //添加添加页面的数据
  handleOk(e) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 1000);
    // this.isAddConfirmLoading = true;
    // this.inValue = "aaaaa";
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    // this.partyBean.currentPage = 1;
    this.query();
  }

  delete() {
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id);
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.partyDeleteListById({ ids: deleteList }); //批量删除
        ob.subscribe(
          () => {
            thiss._notification.create("success", "成功", "删除成功！");
            thiss.partyBean.currentPage = 1;
            thiss.query();
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  //查看维保详情
  showDetail(titleTpl, contentTpl, footerTpl, data) {
    if (data.partyType == "1") {
      this.modal = 2;
      // this.modelTitle = '查看维保单位详情';
      this.modelTitle = "发送通知";
    } else if (data.partyType == "2") {
      this.modal = 3;
      // this.modelTitle = '查看使用单位详情';
      this.modelTitle = "发送通知";
    } else {
      return;
    }
    this.inPartyId = data.id;
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 1000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }
  //查看物业详情
  showDetail_used(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "查看物业详情";
    this.modal = 3;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 1000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传

  showUpload(titleUpload, contentUpload, footerUpload) {
    this.currentModal = this.modalService.open({
      title: titleUpload,
      content: contentUpload,
      footer: footerUpload,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  showBatch(titleBatch, contentBatch, footerBatch) {
    this.currentModal = this.modalService.open({
      title: titleBatch,
      content: contentBatch,
      footer: footerBatch,
      maskClosable: false,
      width: 1000,
      zIndex: 900,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "导入成功");
      }
    }
  }


  download(url: string, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

}
